<template>
    <view class="user-info">
        <u-form :model="form" ref="form1">
		    <u-form-item label="头像">
                <button class="avatar-wrapper u-reset-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                    <image class="avatar" :src="form.avatar"></image>
                </button> 
            </u-form-item>
            <u-form-item label="昵称">
                <input v-model="form.username" @change="nicknamereview" type="nickname" class="weui-input" placeholder="请输入昵称"/>
            </u-form-item>
        </u-form>
        <u-button @click="onSubmit">提交</u-button>
    </view>
</template>
    
<script setup lang='ts'>
import { apiUpload } from '@/api/upload';
import { apiUpdateUser } from '@/api/user';
import { userStore } from '@/store/user';
import { storeToRefs } from 'pinia';
import { ref } from 'vue';

    const defaultavatar = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

    const uStore = userStore();

    const { userInfo } = storeToRefs(uStore)

    const form = ref({
        id: 0,
        username: userInfo.value.username || '',
        avatar: userInfo.value.avatar || defaultavatar
    })

    const onChooseAvatar = (e: any) => {
        console.log(e);
        const { avatarUrl } = e.detail
        uploadImage(avatarUrl);
        // this.setData({
        //     avatar,
        // })
    }
    const uploadImage = (avatar: string) => {
        console.log(avatar);
        if (avatar.indexOf('https') !== -1) {
            form.value.avatar = avatar;
            return;
        }
        apiUpload(avatar).then((res: any) => {
            form.value.avatar = res.data;
        });
    }
    const nicknamereview = (value: any) => {
        console.log(value);
        form.value.username = value.detail.value;
    }
    const onSubmit = () => {
        form.value.id = userInfo.value.id!;
        apiUpdateUser(form.value).then((res: any) => {
            Object.assign(uStore.userInfo, form.value);
            uni.navigateBack();
        })
    }
</script>
    
<style scoped lang="scss">
    .avatar-wrapper {
        text-align: right;
        .avatar {
            border-radius: 50%;
            height: 100rpx;
            width: 100rpx;
            margin-right: 0;
        }
    }
    .user-info  {
        padding: 0 32rpx;
    }
</style>